package com.cms.init;

import com.cms.common.model.entity.AdminUser;
import com.cms.common.model.services.AdminUserService;
import com.cms.common.model.services.PermissionService;
import com.cms.common.utils.MD5Util;
import com.cms.html.TemplateEngineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.security.NoSuchAlgorithmException;


@Component
@Order(value = 1)
public class StartupRunner implements CommandLineRunner {


    @Value("${super-admin.account}")
    private String account;

    @Value("${super-admin.password}")
    private String password;

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    PermissionService permissionService;


    @Override
    public void run(String... args) throws Exception {
        TemplateEngineService.initTemplatePath();
        addAdminUser();
        permissionService.initPermission();

    }

    //初始化超管
    private void addAdminUser() {
        //增加超管
        AdminUser adminUser = adminUserService.getAdminUserByUsername(account);
        if (adminUser == null) {
            adminUser = new AdminUser();
            adminUser.setUsername(account);
            String salt = "";
            try {
                salt = MD5Util.MD5Encode(account + password + System.currentTimeMillis());
                adminUser.setSalt(salt);
                adminUser.setPassword(adminUserService.encodePwd(account, password, salt));
                adminUserService.insertAdminUser(adminUser);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
    }


}